<template>
  <div>
    <div id="map-container"></div>
    <div>{{ center }}</div>
    <!-- 显示中心经纬度 -->
  </div>
  <p>最新订单</p>
  <IndexOrder
    :latitude="latitude"
    :longitude="longitude"
    @custom-event="handleEvent"
  ></IndexOrder>
</template>

<script>
import { load } from "@amap/amap-jsapi-loader";
import IndexOrder from "./index_order.vue";

export default {
  components: {
    IndexOrder,
  },
  data() {
    return {
      center: "3", // 用于存储中心经纬度
      map: null, // 地图实例对象
      longitude: "117",
      latitude: "39",
    };
  },
  mounted() {
    load({
      key: "f819c82141a53cedf6c86346c694e12f",
      version: "2.0",
      plugins: ["AMap.Geolocation"],
    })
      .then((AMap) => {
        this.map = new AMap.Map("map-container", {
          latitude: this.latitude,
          longitude: this.longitude,
          zoom: 100,
        });

        // 创建标志对象
        this.marker = new AMap.Marker({
          position: this.map.getCenter(), // 设置标志位置为地图中心点
          draggable: true, // 设置标志为可拖动
        });

        this.marker.setMap(this.map); // 将标志添加到地图上

        // 监听标志拖动事件，更新中心点坐标
        this.marker.on("dragend", (event) => {
          const center = event.target.getPosition();
          this.center = `中心经度：${center.lng}，中心纬度：${center.lat}`;
          this.longitude = center.lng;
          this.latitude = center.lat;
        });

        // 监听地图移动事件，更新标志位置
        this.map.on("moveend", () => {
          const center = this.map.getCenter();
          this.marker.setPosition(center);
          this.center = `中心经度：${center.lng}，中心纬度：${center.lat}`;
          this.longitude = center.lng;
          this.latitude = center.lat;
        });
      })
      .catch((error) => {
        // console.log('加载高德地图失败：', error);
      });
  },
};
</script>
